package com.finger.service.impl;

import com.finger.dao.UserDao;
import com.finger.pojo.User;
import com.finger.pojo.UserLearnedWord;
import com.finger.pojo.dto.UserRankingDto;
import com.finger.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    //用户注册功能
    public String register(String username, String password) {
        //首先根据用户名查询当前用户名是否已经存在
        Boolean usernameExist = userDao.getUserByUsername(username);
        if (usernameExist == null){
            //如果用户名不存在,继续执行注册逻辑
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            //用户成就初始化为小白
            user.setAchievement("小白");
            //执行持久化操作
            Boolean flag = userDao.addUser(user);
            if (flag == null) {
                //添加失败逻辑
                return "注册失败";
            }else {
                //添加成功逻辑
                return "注册成功";
            }
        }else {
            //用户名存在逻辑
            return "用户名已存在";
        }
    }

    @Override
    //用户登录功能
    public User login(String username, String password) {
        User user = userDao.getUserByUsernameAndPassword(username, password);
        if (user == null) {
            //用户不存在
            return null;

        }else {
            //用户信息存在，用户信息作为验证信息存储在session中
            return user;
        }
    }

    @Override
    //通过用户id获取用户信息
    public User getUserById(Integer id) {
        return userDao.getUserById(id);
    }

    @Override
    public List<UserRankingDto> getUserRanking() {
        List<UserRankingDto> userRankingDtos = new ArrayList<>(); // 创建一个空的泛型列表
        List<User> allUser = userDao.getAllUser();
        for (User user : allUser) {
            UserRankingDto temp = new UserRankingDto();
            temp.setUsername(user.getUsername());
            temp.setAchievement(user.getAchievement());
            List<UserLearnedWord> learnedWordsByUid = userDao.getUserLearnedWordsByUid(user.getId());
            Integer tempNum = 0;
            for (UserLearnedWord learnedWord : learnedWordsByUid) {
                tempNum += learnedWord.getCount();
            }
            temp.setNum(tempNum);
            userRankingDtos.add(temp);
        }
        // 使用 Comparator 接口对列表进行排序
        Collections.sort(userRankingDtos, Comparator.comparingInt(UserRankingDto::getNum).reversed());
        return userRankingDtos;
    }
}
